package com.dongdong.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.exception.LoginException;
import com.dongdong.pojo.TbSeller;
import com.dongdong.pojo.User;
import com.dongdong.service.TbSellerService;
import com.dongdong.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class UserRealm extends AuthorizingRealm {
    @Reference
    private TbSellerService tbSellerService;
//    @Reference
//    private MenuService menuService;
    //登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        //假设数据库账号密码
        //判断账号或者密码
        //1.判断用户名

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        TbSeller tbSeller = tbSellerService.getInfoLogin(token.getUsername());
        if (tbSeller ==null){
                return null;
            }
       // 0 待审核   1审核通过  2 审核不通过 3 封号
        if ( !tbSeller.getStatus().equals("1")){
         //抛出异常
          throw  new LoginException("无法登录,账号异常[可能是封号]");
        }

            //判断密码
        return new SimpleAuthenticationInfo(tbSeller,tbSeller.getPassword(), ByteSource.Util.bytes(tbSeller.getSalt()),"");
    }

    //权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        //动态的去授权
//        TPerson tPerson = (TPerson) SecurityUtils.getSubject().getPrincipal();
//        // 根据用户id查询当前用户所拥有的字符串
////       List<String>perms =  menuService.findPermission(tPerson.getPid());
//
//        //授权
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;

    }

}
